﻿/*  
    作者:Devil月哥
    制作日期:2012年11月13日
    文件功能:DES加密解密
    修改日期:
    修改内容:
            Des加密解密功能类
    遗留问题:
*/
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Kernel.Encrypt
{
    /// <summary>
    /// Des加密解密类
    /// </summary>
    public class Des
    {
        #region 构造函数
        /// <summary>
        /// Des加密解密构造函数
        /// </summary>
        public Des() { }
        #endregion

        #region 变量
        /// <summary>
        /// KEY需8位数
        /// </summary>
        private static string key = "zyhwq1314";
        #endregion

        #region 对称加密解密的密钥
        /// <summary>
        /// 对称加密解密的密钥
        /// </summary>
        public static string Key
        {
            get
            {
                return key;
            }
            set
            {
                key = value;
            }
        }
        #endregion

        #region DES加密
        /// <summary>
        /// DES加密(加密解密前先设置密钥)
        /// </summary>
        /// <param name="encryptString"></param>
        /// <returns></returns>
        public static string DesEncrypt(string encryptString)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            byte[] keyIV = keyBytes;
            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String(mStream.ToArray());
        }
        #endregion

        #region DES解密
        /// <summary>
        /// DES解密(加密解密前先设置密钥)
        /// </summary>
        /// <param name="decryptString"></param>
        /// <returns></returns>
        public static string DesDecrypt(string decryptString)
        {
            try
            {
                byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
                byte[] keyIV = keyBytes;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
